package com.wbl.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wbl.gulimall.product.mapper.CategoryMapper;
import com.wbl.gulimall.product.vo.CategoryVo;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wbl.gulimall.common.utils.PageUtils;
import com.wbl.gulimall.common.utils.Query;

import com.wbl.gulimall.product.entity.CategoryEntity;
import com.wbl.gulimall.product.service.CategoryService;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryVo> listWithTree() {
        // 1.查询出所有的分类
        List<CategoryEntity> allCategoryMenu = this.list();
        // 2.将entity对象转换为vo对象
        List<CategoryVo> categoryVos = BeanUtil.copyToList(allCategoryMenu, CategoryVo.class);
        // 3.将查询出来的树形结构进行返回
        return categoryVos.stream()
                // 1.过滤出所有的根菜单
                .filter(menu -> menu.getParentCid() == 0)
                // 2.将查询出来的分类组装成父子结构的树形结构
                .peek(menu -> menu.setChildren(getChildrenMenus(menu,categoryVos)))
                // 3.进行菜单之间的排序
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public int removeMenuByIds(List<Long> categoryIds) {
        // todo 需要校验商品菜单是否被引用


        return baseMapper.deleteBatchIds(categoryIds);
    }

    /**
     * 查找对应节点的子节点菜单
     * @param rootMenu 上级菜单对象
     * @param allMenu 所有的菜单对象
     * @return 子节点菜单
     */
    private List<CategoryVo> getChildrenMenus(CategoryVo rootMenu,List<CategoryVo> allMenu){
        return allMenu.stream()
                // 根节点的id和所有菜单中的父节点的id相同
                .filter(menu -> Objects.equals(menu.getParentCid(), rootMenu.getCatId()))
                // 递归调用查询子菜单的方法
                .peek(menu -> menu.setChildren(getChildrenMenus(menu, allMenu)))
                // 子菜单之间进行排序
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

}